package com.rdc.example.dao.impl;

import com.rdc.example.entity.Like;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.rdc.example.util.DBUtil.closeResources;
import static com.rdc.example.util.DBUtil.getConnection;


/**
 * @author duck
 */
public class LikeDaoImpl implements com.rdc.example.dao.LikeDao {
    /**
     *
     * @param userId
     * @param articleId
     * @return
     * @throws Exception
     */
    @Override
    public boolean insertLike(Integer userId, Integer articleId) throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = getConnection();
            String sql = "INSERT INTO `like` (user_id, article_id) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.setInt(2, articleId);
            int row = pstmt.executeUpdate();
            return row > 0;
        } catch (SQLException e) {
            if (e.getErrorCode() == 1062) {
                System.out.println("重复点赞: user=" + userId + ", article=" + articleId);
            } else {
                e.printStackTrace();
            }
            return false;
        } finally {
            closeResources(null, pstmt, conn);
        }
    }

    /**
     *
     * @param userId
     * @param articleId
     * @return
     * @throws Exception
     */
    @Override
    public boolean deleteLike(Integer userId, Integer articleId) throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = getConnection();
            String sql = "DELETE FROM `like` WHERE user_id = ? AND article_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.setInt(2, articleId);
            int row = pstmt.executeUpdate();
            return row > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(null, pstmt, conn);
        }
    }

    /**
     *
     * @param articleId
     * @return
     * @throws Exception
     */
    @Override
    public boolean deleteLikeByArticleId(Integer articleId) throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = getConnection();
            String sql = "delete from `like` where  article_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, articleId);
            int row = pstmt.executeUpdate();
            return row > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(null, pstmt, conn);
        }
    }

    /**
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public List<Like> listLikeByUserId(Integer userId) throws Exception {
        Connection conn = getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Like> likeList = new ArrayList<>();
        try {
            // 按用户ID查询（区别于评论的按文章ID查询）
            String sql = "SELECT * FROM `like` WHERE user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                likeList.add(convertToLike(rs));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources(rs, pstmt, conn);
        }
        return likeList;
    }

    /**
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @Override
    public List<Integer> listArticleIdByUserId(Integer userId) throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Integer> articleIds = new ArrayList<>();

        try {
            conn = getConnection();
            // 直接查询文章ID字段（相比listLikeByUserId减少数据量）
            String sql = "select article_id from `like` where user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();

            // 遍历结果集提取文章ID（无需完整对象转换）
            while (rs.next()) {
                articleIds.add(rs.getInt("article_id"));
            }
        } catch (SQLException e) {
            // 保持与其他方法一致的异常处理
            throw new RuntimeException("查询用户点赞文章失败", e);
        } finally {
            // 复用现有的资源关闭方法
            closeResources(rs, pstmt, conn);
        }

        return articleIds;
    }

    /**
     *
     * @param userId
     * @param articleId
     * @return
     * @throws Exception
     */
    @Override
    public boolean likeCheck(Integer userId, Integer articleId) throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            String sql = "select count(*) from `like` where user_id = ? and article_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.setInt(2, articleId);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                int count = rs.getInt(1);
                return count > 0;
            }
            return false;
            }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources(rs, pstmt, conn);
        }
    }

    /**
     *
     * @param rs
     * @return
     * @throws SQLException
     */


    private Like convertToLike(ResultSet rs) throws SQLException {
        Like like = new Like();
        like.setId(rs.getInt("id"));
        like.setUserId(rs.getInt("user_id"));
        like.setArticleId(rs.getInt("article_id"));
        Timestamp timestamp = rs.getTimestamp("created_at");
        if (timestamp != null) {
            like.setCreatedAt(timestamp.toLocalDateTime());
        }
        return like;
    }


}
